<script setup lang="ts">
import { addShopCar, deleteCar } from "~/api/goods";
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { useSocketStore } from "~/store/useSocket";
import { useUserStore } from "~/store/useUser";
import { Loading } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";

const router = useRouter();
const userStore = useUserStore();
const socketStore = useSocketStore();
const props = defineProps({
  details: {
    type: Object,
    default: () => ({}),
  },
});

const officialVersion = ref({}); // 正式版信息
const trialVersion = ref({}); // 体验版信息
onMounted(() => {
  if (props.details.standard) {
    officialVersion.value = props.details.standard;
    trialVersion.value = props.details.experience || {};
  }
});

const varInfo = computed(() => {
  if (varIndex.value === 1) {
    return officialVersion.value;
  } else {
    return trialVersion.value;
  }
});

const detailsServer = computed(() => {
  if (!varInfo.value.detailsServer) {
    return [];
  }
  return varInfo.value.detailsServer.filter((item: any) => item.content);
});

// 是否已加入购物车，基于当前选择版本的 inCart 字段
const addCutStatus = computed(() => {
  const current = varInfo.value as any;
  return !!current?.inCart;
});
const addCut = async () => {
  // 检查用户是否已登录
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录后再加入购物车');
    router.push('/login');
    return;
  }
  
  try {
    if (addCutStatus.value) {
      const data = await deleteCar({
        goodsId: props.details.baseInfo.id,
        skuType: varIndex.value
      });
    } else {
      const data = await addShopCar({
        goodsId: props.details.baseInfo.id,
        quantity: 1, // 添加数量参数，默认为1
        skuType: varIndex.value // 添加版本参数：1-标准版，2-体验版
      });
    }
    // 同步更新当前所选版本的 inCart 状态
    if (varIndex.value === 1) {
      (officialVersion.value as any).inCart = !addCutStatus.value;
    } else {
      (trialVersion.value as any).inCart = !addCutStatus.value;
    }
  } catch (e) {
    console.log(e);
  }
};

const buyNow = () => {
  // 检查用户是否已登录
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录后再购买');
    router.push('/login');
    return;
  }
  
  router.push(`/buyGoods?id=${props.details.baseInfo.id}&ver=${varIndex.value}`);
};
//
const varIndex = ref(1);
const selectVar = (index) => {
  if (index === 2 && !trialVersion.value.id) {
    return ElMessage.warning("当前商品未提供体验版");
  }
  varIndex.value = index;
};
// 立即咨询
const createChatStatus = ref(false);
const toIM = () => {
  if (createChatStatus.value) {
    return;
  }
  createChatStatus.value = true;
  if (!userStore.getToken) {
    router.push("/login");
    return;
  }
  if (props.details.baseInfo.uimKey) {
    socketStore.setCurrentImKey(props.details.baseInfo.uimKey);
    socketStore.sendMessage(
      "chatMsg",
      {
        to: props.details.baseInfo.uimKey,
        content: "现在可以开始沟通了",
        contentType: 4,
        exData: {
          goodsInfo: props.details.baseInfo,
          trialVersion: varIndex.value === 1 ? officialVersion.value : trialVersion.value,
        },
      },
      () => {
        setTimeout(() => {
          createChatStatus.value = false;
          router.push(`/chat?id=${props.details.baseInfo.id}&type=4`);
        }, 1000);
      }
    );
  }
};
// 开启服务时间
// 根据 startServiceTimes 显示：0:24小时内，1:3天内，2:7天内，3:任何时候
const startTime = computed(() => {
  // 确保 baseInfo 存在
  if (!props.details?.baseInfo) {
    return "马上到岗";
  }
  
  // 使用 startServiceTimes 字段
  const startServiceTimes = props.details.baseInfo.startServiceTimes;
  
  // 将 startServiceTimes 转换为数字，处理字符串 "0" 的情况
  const timeType = Number(startServiceTimes);
  
  // 检查是否为有效数字（不是 NaN）
  if (isNaN(timeType) || startServiceTimes === undefined || startServiceTimes === null) {
    return "马上到岗";
  }
  
  switch (timeType) {
    case 0:
      return "24小时内";
    case 1:
      return "3天内";
    case 2:
      return "7天内";
    case 3:
      return "任何时候";
    default:
      return "马上到岗";
  }
});
</script>

<template>
  <div class="goods-select">
    <div class="tab">
      <span :class="{ active: varIndex === 1 }" @click="selectVar(1)">标准版</span>
      <span :class="{ active: varIndex === 2 }" @click="selectVar(2)">体验版</span>
    </div>
    <div class="goods-class" :style="{ borderBottom: props.details.baseInfo.auditStatus ? '1px solid #ededee' : 'none' }">
      <p class="price"><span>¥</span>{{ varInfo.goodsAmount }}</p>
      <p class="tips">{{ varInfo.introduce }}</p>
      <p class="you-have">您将得到</p>
      <p class="goods-item" v-for="item of detailsServer" :key="item.id">
        <span class="r"></span>
        <span class="text">{{ item.content }}</span>
        <img src="~/assets/goods-select.png" alt="" />
      </p>
      <p class="deliver">
        <span class="deliver-1">交付周期</span>
        <span class="deliver-2">{{ varInfo.deliverDays }}天</span>
      </p>
      <p class="deliver">
        <span class="deliver-1">开启服务时间</span>
        <span class="deliver-2">{{ startTime }}</span>
      </p>
    </div>
    <div class="buy" v-if="props.details.baseInfo.auditStatus">
      <div class="buy-cut" :class="{ active: addCutStatus }" @click="addCut">
        <img v-if="addCutStatus" src="~/assets/buy-cut-active.png" alt="" />
        <img v-else src="~/assets/buy-cut.png" alt="" />
        <span>{{ addCutStatus ? "已加购物车" : "加入购物车" }}</span>
      </div>
      <!--
      <div class="to-service" @click="toIM">
        <el-icon v-if="createChatStatus" size="14" class="loading-gif">
          <Loading />
        </el-icon>
        <span>立即咨询</span>
        <img class="service-qrcode" src="~/assets/show-service.png" alt="" />
      </div>
      -->
      <div class="but-now" @click="buyNow">立即购买</div>
    </div>
  </div>
  <p class="report" v-if="props.details.baseInfo.auditStatus"><NuxtLink to="#">举报Ta</NuxtLink></p>
</template>

<style scoped lang="scss">
.goods-select {
  min-height: 550px;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin-top: 16px;
  display: flex;
  flex-direction: column;
}
.tab {
  display: flex;
  span {
    font-weight: bold;
    cursor: pointer;
    flex: 1;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(25, 30, 40, 0.02);
    box-sizing: border-box;
    &:first-child {
      border-top-left-radius: 16px;
    }
    &:last-child {
      border-top-right-radius: 16px;
    }
    &.active {
      background: #ffffff;
      border-bottom: 2px solid rgba(29, 191, 115, 1);
      border-right: 1px solid #ededee;
    }
  }
}
.goods-class {
  flex: 1;
  margin: 20px 24px;
  box-sizing: border-box;
  border-bottom: 1px solid #ededee;
  .price {
    color: rgba(255, 79, 79, 1);
    font-size: 30px;
    font-weight: bold;
    margin-bottom: 6px;
    span {
      font-size: 20px;
    }
  }
  .tips {
    color: rgba(25, 30, 40, 0.6);
    margin-bottom: 20px;
  }
  .you-have {
    color: #191e28;
    font-weight: bold;
    font-size: 15px;
    margin-bottom: 8px;
  }
  .goods-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .r {
      width: 4px;
      height: 4px;
      background: rgba(25, 30, 40, 0.1);
      border-radius: 100%;
      margin-right: 4px;
    }
    .text {
      flex: 1;
      color: #191e28;
    }
    img {
      width: 20px;
      height: 20px;
    }
  }
  .deliver {
    display: flex;
    align-items: center;
    margin-top: 16px;
    margin-bottom: 18px;
    color: #191e28;
    font-weight: bold;
    .deliver-1 {
      flex: 1;
    }
    .deliver-2 {
      color: #1dbf73;
    }
  }
}
.buy {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px 24px;
  .buy-cut {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    user-select: none;
    transition: all 0.3s;
    &.active {
      span {
        color: rgba(29, 191, 115, 1);
      }
    }
    img {
      width: 24px;
      height: 24px;
      margin-bottom: 4px;
    }
    span {
      color: #191e28;
    }
  }
  .to-service {
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #1dbf73;
    flex: 0 0 138px;
    height: 48px;
    cursor: pointer;
    user-select: none;
    transition: all 0.1s;
    &:hover {
      border: 1px solid #008571;
      span {
        color: #008571;
      }
    }
    span {
      transition: all 0.1s;
      color: #1dbf73;
      font-size: 16px;
      line-height: 16px;
      font-weight: bold;
      padding-right: 14px;
      margin-right: 14px;
      border-right: 1px solid rgba(232, 240, 236, 1);
    }
    .loading-gif {
      width: 14px;
      height: 14px;
      color: #1dbf73;
      font-weight: bold;
      animation: rotate 1s linear infinite;
    }
    .service-qrcode {
      width: 16px;
      height: 16px;
    }
  }
  .but-now {
    cursor: pointer;
    flex: 0 0 200px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #1dbf73;
    border-radius: 8px 8px 8px 8px;
    font-size: 16px;
    color: #ffffff;
    font-weight: bold;
    user-select: none;
    transition: all 0.1s;
    &:hover {
      background: #008571;
    }
  }
}
.report {
  margin-top: 24px;
  text-align: right;
  cursor: pointer;
  a {
    color: rgba(25, 30, 40, 0.36);
    text-decoration: none;
  }
}
</style>
